<?php
/**
 * 【购物车】添加接口
 * @author webopenfather
 */

// 导入公共库文件
include '../../util/function.php';
include '../../util/db.php';
include '../../util/token.php'; // 这个文件中声明了$userId

// 1. 接受数据
$goodsId = @$_REQUEST['goodsId'];
if (!$goodsId) response(400, '参数有误');
$buyNum = @$_REQUEST['buyNum'] ? $_REQUEST['buyNum'] : 1;

// 检测参数是否真实
$pdoStatement = $pdo->query("select * from ecs_goods where goods_id = {$goodsId}");
$goodsInfo = $pdoStatement->fetch(PDO::FETCH_ASSOC);
if (!$goodsInfo) response(400, '参数有误-商品不存在');
if ($goodsInfo['goods_number'] < $buyNum ) response(400, "【{$goodsInfo['goods_name']}】库存不足");

// 2. 操作数据库（注：$pdo变量在db.php文件中定义了 所以可以直接用）

    // 1. 检测购物车表是否存在：存在-更新，不存在-插入
    $pdoStatement = $pdo->query("select * from ecs_cart where user_id = {$userId} and goods_id = {$goodsId}");
    $isFind = $pdoStatement->fetch(PDO::FETCH_ASSOC);

    if ($isFind)
    {// 更新购物车
        $rs = $pdo->exec("update ecs_cart set goods_number = goods_number+1 where user_id = {$userId} and goods_id = {$goodsId}");
    } else {
    // 插入
        $goodsName = $goodsInfo['goods_name'];
        $marketPrice = $goodsInfo['market_price'];
        $shopPrice = $goodsInfo['shop_price'];
        $rs = $pdo->exec("insert into ecs_cart 
        (
            user_id, goods_id, goods_name, 
            market_price, goods_price, goods_number)
            values
        (
            {$userId}, {$goodsId}, '{$goodsName}',
            '{$marketPrice}', '{$shopPrice}', {$buyNum}
        )");
    }
    
// 3. 响应数据
if ($rs) {
    response(201, '操作成功');
} else {
    response(500, '操作失败');
}
